package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.supplier.R;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.ToastUtils;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class ForgetPasdActivity extends BaseActivity {

	public Context mContext;
	public static final String TAG = "ForgetPasdActivity";
	// 手机号,验证码，密码
	private String phoneSting, codeString,passwordString;
	private EditText phoneEt;
	private EditText codeEt;
	private EditText passwordEt;
	private TextView getcodeTv;
	private Button sureBu;

	private ImageView look_password;
	private FrameLayout look_frame;
	private boolean isRequestCode;
	private boolean isDestory;

	private int currentRestTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forget_pasd);
		phoneEt = (EditText)findViewById(R.id.phone_number);
		codeEt = (EditText)findViewById(R.id.code_number);
		passwordEt = (EditText)findViewById(R.id.password_number);
		sureBu = (Button)findViewById(R.id.sure);
		look_frame = (FrameLayout)findViewById(R.id.look_frame);
		look_password = (ImageView)findViewById(R.id.look_password);
		getcodeTv = (TextView)findViewById(R.id.get_code);
		sureBu.setOnClickListener(this);
		look_frame.setOnClickListener(this);
		getcodeTv.setOnClickListener(this);

		passwordEt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

			}

			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

			}

			@Override
			public void afterTextChanged(Editable editable) {
				String s = editable.toString();


				if (VerificationUtils.isContainChinese(s)) {
					toast("密码不能包括中文");
				}
				if (!VerificationUtils.isValid(s)) {
					toast(getString(R.string.illegal_input, "密码"));
					return;
				}
			}
		});

		//setContentView(R.layout.activity_register);
		//ToastUtils.TextToast(getApplicationContext(), "前期阶段，无验证码亦可!");
		mContext = this;
		initData();
		initView();
		baseback.setVisibility(View.VISIBLE);
		getLastTime();
	}

	public void getLastTime() {
		SharedPreferences sp = FileUtil.getSharedPreferences();
		String phone = sp.getString("phone_num_code", "");
		long lastTimeMills = sp.getLong("current_time_code", 0);
		int restTime = sp.getInt("current_rest_time_code", 0);
		long dff = System.currentTimeMillis() - lastTimeMills;
		if (!TextUtils.isEmpty(phone) && phone.equals(phoneEt.getText().toString()) && dff > 0 && dff < restTime * 1000 && restTime < 60) {
			currentRestTime = (int) (restTime - dff / 1000);
			getcodeTv.setText(currentRestTime + "秒后重新发送");
			getCodeControl();
		}
	}

	private void initData() {
		basetitle.setText("修改密码");
		SharedPreferences user = getSharedPreferences(
				"userinfo", Activity.MODE_PRIVATE);
		String mobile = user.getString("mobile","");
		if(mobile!=null){
			phoneEt.setText(mobile);
			phoneEt.setSelection(phoneEt.getText().length());
		}

	}


	private void initView() {
	/*	Selflistener selflistener = new Selflistener();
		getcodeTv.setOnClickListener(selflistener);
		sureBu.setOnClickListener(selflistener);*/
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (isDestory) {
				return;
			}
			int i = msg.arg1;
			if (i >= 1) {
				getcodeTv.setClickable(false);
				getcodeTv.setText(i + "秒后重新发送");
			} else {
				i = 0;
				getcodeTv.setClickable(true);
				getcodeTv.setText(R.string.getcode_regist);
			}
			currentRestTime = i;
		};
	};
	boolean passwordflag = false;
	String password = "";

	@Override
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.baseback:
				// 返回上一页
				finish();
				break;
			case R.id.look_frame:
				if (!passwordflag) {

					look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03_));
					passwordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				} else {
					look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03));

					passwordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
				}
				passwordflag = !passwordflag;
				passwordEt.postInvalidate();
				CharSequence text = passwordEt.getText();
				if (text instanceof Spannable) {
					Spannable spanText = (Spannable) text;
					Selection.setSelection(spanText, text.length());
				}
				break;


			case R.id.get_code:
				// 获取验证码
				getcodeTv.setClickable(false);
				if (InputControl.isPhoneNumber(phoneEt) && !isRequestCode) {
					//isAccount();
					//getCodeControl();
					currentRestTime = 60;
					getcodeTv.setText(R.string.getcode_registing);
					isRequestCode = true;
					getCodePost();
				} else {
					ToastUtils.TextToast(getApplicationContext(), "请输入正确的手机号");
					getcodeTv.setClickable(true);
				}

				break;
			case R.id.sure:
				if(InputControl.isEmpty(phoneEt)){
					T.toast("请输入手机号");
					return;
				}else {
					if (!InputControl.isPhoneNumber(phoneEt)) {
						T.toast("请输入正确的手机号");
						return;
					}
				}
				if(InputControl.isEmpty(codeEt)||codeEt.getText().toString().length()!=4){
					T.toast("请输入4位验证码");
					return;
				}
				if(InputControl.isEmpty(passwordEt)||passwordEt.getText().toString().length()<6){
					T.toast("请输入长度至少为6位的密码");
					return;
				}
				if (VerificationUtils.isContainChinese(passwordEt.getText().toString())) {
					toast("密码不能包括中文");
					return;
				}
				if (!VerificationUtils.isValid(passwordEt.getText().toString())) {
					toast(getString(R.string.illegal_input, "密码"));
					return;
				}
				register();
				break;
			default:
				break;
		}
	}

	/**
	 * 获取验证码按钮倒计时控制
	 */
	private void getCodeControl() {
		//getCode();
		new Thread() {
			public void run() {
				try {
					while (currentRestTime > 0) {
						if (isDestory) {
							return;
						}
						Thread.sleep(999);
						currentRestTime--;
						Message message = new Message();
						message.arg1 = currentRestTime;
						handler.sendMessage(message);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			};
		}.start();
	}
	/** 获得验证码 */
	OnRequestListener<StatusEntity> onRequestListener = new OnRequestListener<StatusEntity>() {
		@Override
		public StatusEntity jsonToObj(String responseStr) {
			return new Gson().fromJson(responseStr, StatusEntity.class);
		}

		@Override
		public void onFail(int failCode, Object arg, Object tag) {
		}

		@Override
		public void onResponseError(int failCode, Object arg, Object tag) {
		}

		@Override
		public void onStart(Object tag) {
		}
		@Override
		public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
			StatusEntity responseElement = response.getResponseElement();
			if (responseElement.isSuccess()) {
				Intent main = new Intent(getApplicationContext(), LoginActivity.class);
				main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// 清空已存在的所有Activity
				startActivity(main);
				finish();

			}else {

			}
		}
	};

	/**
	 * 注册
	 */
	private void register() {

		RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
		data.setCmd(AppSupplyRouterConstant.CMD_UPDATE);
		data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
		Map<String, String> map = new HashMap<>();
		map.put("phone", phoneEt.getText().toString());
		map.put("password", passwordEt.getText().toString());
		map.put("verification", codeEt.getText().toString());
		data.setParameters(map);
		request(data, "register", onRequestListener);
	}
	OnRequestListener<StatusEntity> onRequestCodeListener = new OnRequestListener<StatusEntity>() {
		@Override
		public StatusEntity jsonToObj(String responseStr) {
			return new Gson().fromJson(responseStr, StatusEntity.class);
		}

		@Override
		public void onFail(int failCode, Object arg, Object tag) {
			isRequestCode = false;
			getcodeTv.setClickable(true);
			getcodeTv.setText(R.string.getcode_regist);
		}

		@Override
		public void onResponseError(int failCode, Object arg, Object tag) {
			//token超时
			isRequestCode = false;
			getcodeTv.setClickable(true);
			getcodeTv.setText(R.string.getcode_regist);
		}

		@Override
		public void onStart(Object tag) {

		}
		@Override
		public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
			isRequestCode = false;
			StatusEntity responseElement = response.getResponseElement();
			if (responseElement.isSuccess()) {
				getcodeTv.setClickable(false);
				getCodeControl();
			}else {

				getcodeTv.setText(R.string.getcode_regist);
			}
			return;
		}
	};

	/**
	 * 注册
	 */
	private void getCodePost() {

		RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
		data.setCmd(AppSupplyRouterConstant.CMD_GETCODE);
		data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
		Map<String, String> map = new HashMap<>();
		map.put("phone", phoneEt.getText().toString());
		map.put("type", "2");
		data.setParameters(map);
		request(data, "getVerification", onRequestCodeListener);
	}

	@Override
	protected void onDestroy() {
		isDestory = true;
		RequestManager.getInstance().cancel("register");
		onRequestListener = null;
		RequestManager.getInstance().cancel("getVerification");
		onRequestCodeListener = null;
		super.onDestroy();
	}
}